package com.ihrm.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ihrm.common.utils.IdWorker;
import com.ihrm.domain.system.*;
import com.ihrm.system.mapper.PermissionMapper;
import com.ihrm.system.mapper.RoleMapper;
import com.ihrm.system.mapper.RolePermissionMapper;
import com.ihrm.system.service.api.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private IdWorker idWorker;

    @Override
    public void add(Role role) {
        String id = idWorker.nextId() + "";
        role.setId(id);
        roleMapper.insertSelective(role);
    }

    @Override
    public void update(Role role) {
        roleMapper.updateByPrimaryKeySelective(role);
    }

    @Override
    public void deleteById(String id) {
        roleMapper.deleteByPrimaryKey(id);

    }

    @Override
    public Role findById(String id) {
        return roleMapper.selectRoleAndPermByPrimaryKey(id);
    }


    @Override
    public PageInfo<Role> getRoleListPageInfo(String companyId, int page, int size) {
        // 1.开启分页功能
        PageHelper.startPage(page, size);
        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andCompanyIdEqualTo(companyId);
        List<Role> roles = roleMapper.selectByExample(roleExample);
        // 3.为了方便页面使用将 roles 封装为
        PageInfo<Role> pageInfo = new PageInfo<>(roles);
        return pageInfo;
    }


    @Override
    public void assignPerms(String roleId, List<String> permIds) {
        //1.根据id查询角色
        Role role = roleMapper.selectRoleAndPermByPrimaryKey(roleId);
        //2.设置角色的权限集合
        RolePermissionExample rolePermissionExample = new RolePermissionExample();
        RolePermissionExample.Criteria criteria = rolePermissionExample.createCriteria();
        criteria.andRoleIdEqualTo(roleId);
        rolePermissionMapper.deleteByExample(rolePermissionExample);

        for (String permId : permIds) {
            RolePermissionKey rolePermissionKey = new RolePermissionKey(roleId, permId);
            rolePermissionMapper.insert(rolePermissionKey);
        }

    }

    @Override
    public List<Role> findAll() {
        return roleMapper.selectByExample(new RoleExample());
    }
}
